//
//  BaseNetManager.m
//  Btpin
//
//  Created by Vic on 2019/3/10.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "BaseNetManager.h"

static BaseNetManager *manager = nil;
static dispatch_once_t onceToken;

@implementation BaseNetManager

+ (instancetype)sharedManager {
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
        manager.requestSerializer.timeoutInterval = RequestTimeOutInterval;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", @"image/png", @"image/jpeg", @"application/x-www-form-urlencoded", nil];
        // 设置header
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    });
    return manager;
}

- (void)requestWithMethod:(RequestMethod)method path:(NSString *)path params:(NSDictionary *)params successBlock:(requestSuccessBlock)success failurBlock:(requestFailureBlock)failure {
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    [UIApplication sharedApplication].keyWindow.userInteractionEnabled = NO;
    
    switch (method) {
        case GET:{
//            [self GET:path parameters:params progress:nil success:^(NSURLSessionTask *task, NSDictionary * responseObject) {
//                NSLog(@"JSON: %@", responseObject);
//                success(responseObject);
//                [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
//            } failure:^(NSURLSessionTask *operation, NSError *error) {
//                NSLog(@"Error: %@", error);
//                failure(error);
//                [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
//            }];
            [self GET:path parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSLog(@"JSON: %@", responseObject);
                success(responseObject);
                [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"Error: %@", error);
                failure(error);
                [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
            }];
            break;
        }
        case POST:{
//            [self POST:path parameters:params progress:nil success:^(NSURLSessionTask *task, NSDictionary * responseObject) {
//                NSTimeInterval sec2 = [[NSDate date] timeIntervalSince1970];
//                NSLog(@"path = %@, \ntime load = %f", path, sec2-time);
//                success(responseObject);
//                [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
//            } failure:^(NSURLSessionTask *operation, NSError *error) {
//                NSLog(@"Error: %@", error);
//                failure(error);
//                [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
//            }];
            [self POST:path parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSTimeInterval sec2 = [[NSDate date] timeIntervalSince1970];
                NSLog(@"path = %@, \ntime load = %f", path, sec2-time);
                success(responseObject);
                [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"Error: %@", error);
                failure(error);
                [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
            }];
            break;
        }
        default:
            break;
    }
}
+ (void)requestWithMethod:(RequestMethod)method path:(NSString *)path params:(NSDictionary *)params successBlock:(requestSuccessBlock)success failurBlock:(requestFailureBlock)failure {
    [UIApplication sharedApplication].keyWindow.userInteractionEnabled = NO;
    NSString *requestUrl = path;
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy  timeoutInterval:RequestTimeOutInterval];
    NSString *requestMethod = @"POST";
    switch (method) {
        case POST: {
            requestMethod = @"POST";
        } break;
        case GET: {
            requestMethod = @"GET";
        } break;
        default:
            break;
    }
    [request setHTTPMethod:requestMethod];
    request.timeoutInterval= RequestTimeOutInterval;
    [request setValue:@"application/json;application/octet-stream;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&error];
    if (error) {
        
    }
    
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    } else {
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0, jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    NSData *strData = [mutStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:strData];
    
//    [request setHTTPBody:jsonData];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript", @"text/plain", nil];
    manager.responseSerializer = responseSerializer;
    
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    
//    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//        if (!error) {
//            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//            NSTimeInterval sec2 = [[NSDate date] timeIntervalSince1970];
//            NSLog(@"path = %@, \ntime load = %f", path, sec2-time);
//            NSLog(@"Error: %@", response);
//            success(json);
//            if ([[NSString stringWithFormat:@"%@", json[@"code"]] rangeOfString:@"142"].location == NSNotFound) {
//                
//            } else { // 包含
//                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationForTokenPastDue object:nil];
//            }
//        } else {
//            NSLog(@"Error: %@", error);
//            failure(error);
//        }
//        [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
//    }] resume];
    
    [[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSTimeInterval sec2 = [[NSDate date] timeIntervalSince1970];
            NSLog(@"path = %@, \ntime load = %f", path, sec2-time);
            NSLog(@"Error: %@", response);
            success(json);
            if ([[NSString stringWithFormat:@"%@", json[@"code"]] rangeOfString:@"142"].location == NSNotFound) {
                
            } else { // 包含
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationForTokenPastDue object:nil];
            }
        } else {
            NSLog(@"Error: %@", error);
            failure(error);
        }
        [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
    }] resume];
}
#pragma mark - 字典转string
- (NSString *)convertToJsonData:(NSDictionary *)dict {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    
    if (!jsonData) {
        NSLog(@"%@",error);
    } else {
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
//    NSRange range = {0,jsonString.length};
//    //去掉字符串中的空格
//    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0, mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
}

- (void)deallocManager {
    manager = nil;
    onceToken = 0l;
}

@end
